import { reactive } from "vue";
import { defineStore } from "pinia";
import systemRouter from "../router";
import pinia from "./defaultPinia";
import { usePermissionStore } from "./permissionStore";

export const useAppStore = defineStore("app", () => {
  const app = reactive({
    pageLoading: false,
    openRouters: [],
    currentRouter: {},
  });

  function setPageLoading(bol) {
    app.pageLoading = bol;
  }

  function getPageLoading() {
    return app.pageLoading;
  }

  function addOpenRouters(router) {
    // 当前已打开的路由中添加路由
    if (router.path === "/loginPage") return;
    if (router.meta?.noTagsView) return;
    const hasRouter = app.openRouters.find((item) => {
      return item.path === router.path;
    });
    if (!hasRouter) {
      // 如果当前已打开的路由中没有匹配的路由，则可以塞入
      app.openRouters.push(router);
    }
  }

  function removeOpenRouterItem(router) {
    // 移除tag
    const permissionStore = usePermissionStore(pinia);
    app.openRouters = app.openRouters.filter((item) => {
      return item.path !== router.path;
    });
    if (!app.openRouters.length) {
      // 如果删完了 就返回首页
      // systemRouter.push(home_path)
      const menuList = permissionStore.getMenuList();
      systemRouter.push(menuList[0].path);
    } else {
      systemRouter.push(app.openRouters[0].path);
    }
  }

  function removeAllOpenRouter() {
    // 清空全部已经打开的路由
    app.openRouters = [];
  }

  function saveCurrentRouter(router) {
    app.currentRouter = router;
  }

  function getCurrentRouter() {
    return app.currentRouter;
  }

  function getOpenRouters() {
    return app.openRouters;
  }

  // 关闭其他菜单
  function closeOthersTags() {
    app.openRouters = app.openRouters.filter((item) => {
      return item.path === app.currentRouter.path;
    });
  }

  // 关闭左边的菜单
  function closeLeftTags() {
    const index = app.openRouters.findIndex((item) => {
      return item.path === app.currentRouter.path;
    });
    if (index <= 0) return; // 如果没找到或者是第一个，则不做任何操作
    app.openRouters = app.openRouters.slice(index);
  }

  function closeRightTags() {
    const index = app.openRouters.findIndex((item) => {
      return item.path === app.currentRouter.path;
    });
    if (index < 0) return; // 如果没找到或者是第一个，则不做任何操作
    app.openRouters = app.openRouters.slice(0, index + 1);
  }

  return {
    app,
    setPageLoading,
    addOpenRouters,
    removeOpenRouterItem,
    removeAllOpenRouter,
    saveCurrentRouter,
    closeOthersTags,
    closeLeftTags,
    closeRightTags,
    getPageLoading,
    getCurrentRouter,
    getOpenRouters,
  };
});
